//
//  DataPrinter.cpp
//  sad
//
//  Created by Christopher Kemsley on 4/8/12.
//  Copyright (c) 2012 iAppolopolis. All rights reserved.
//

#include "ModuleFactory.hpp"
#include "Model.hpp"

#include "BusInterface.hpp"
#include "FiFoBuffer.hpp"

#include <stdlib.h>
#include <time.h>

#include <iostream>

#include "Log.hpp"

using namespace FiFo ;







struct DataPrinterSettings : public Settings
{
	std::string		fifoName ;
	std::string		label ;
	bool			doNotPrint ;
	
	DataPrinterSettings ( std::string const & name )
	:	Settings	( name )
	,	fifoName	( )
	,	label		( "Printer" )
		{
		add ( "fifoName" , fifoName ) ;
		add ( "label" , label ) ;
		add ( "doNotPrint" , doNotPrint ) ;
		}
	
	virtual void validate ()
		{
		if ( fifoName.size() == 0 )
			ThrowException ( "DataPrinterSettings" , "FiFo-Name has 0-length" , __FILE__,__LINE__ ) ;
		if ( label.size() == 0 )
			ThrowException ( "DataPrinterSettings" , "Label has 0-length" , __FILE__,__LINE__ ) ;
		}
} ;






template <typename Type>
struct DataPrinter : public ConfiguredModel<DataPrinterSettings>
{
	sc_port <ReadInterface>	mpFifo ;
	
	
	SC_HAS_PROCESS(DataPrinter) ;
	
	DataPrinter ( ModelVariant const & identity )
	:	ConfiguredModel<DataPrinterSettings> ( identity )
		{
		Subscription < ReadInterface >	pFiFo ( mConfig.fifoName ) ;
		bindPortToInterface ( &mpFifo , pFiFo ) ;
		
		srand ( time(0) ) ;
		
		SC_THREAD ( runLoop ) ;
		}
	
	
	void	runLoop ()
		{
		while ( 1 )
			{
			Word	value	=	mpFifo -> read() ;
			Type	v		=	value ;
			
			if ( ! mConfig.doNotPrint )
				Log::output() << mConfig.label << "	" << v ;
			}
		}
	
} ;



TypedModuleMaker< DataPrinter<unsigned> >	bPrinterUnsigned	( "model.test.print.unsigned" ) ;
